package cn.regexp.business.web.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.regexp.common.web.AjaxResult;
import cn.regexp.utils.ResourceUtil;
import cn.regexp.utils.UploadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Controller
@RequestMapping("business")
public class FileUploadController {

    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult upload(MultipartFile file) {
        String aliDomain = ResourceUtil.getConfigByName("oss.aliDomain");
        String imageDir = ResourceUtil.getConfigByName("oss.imageDir");
        try {
            if (ObjectUtil.isEmpty(file)) {
                return AjaxResult.error("请选择图片！");
            }
            String fileName = UploadUtil.uploadAli(file);
            if (ObjectUtil.isEmpty(fileName)) {
                return AjaxResult.error("上传图片失败！");
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", aliDomain + imageDir + fileName);
            return ajax;
        } catch (Exception e) {
            log.error("上传图片失败！错误信息：{}", e.getMessage());
            return AjaxResult.error("上传图片失败！");
        }
    }
}
